package singsong;

import java.util.ArrayList;
import java.util.List;

public class PiecewiseAudioClip implements AudioClip {

	private final List<AudioClip> clips;
	
	public PiecewiseAudioClip() {
		clips = new ArrayList<AudioClip>();
	}
	
	public PiecewiseAudioClip(List<AudioClip> clips) {
		this.clips = clips;
	}
	
	public void Append(AudioClip clip) {
		clips.add(clip);
	}
	
	public void Prepend(AudioClip clip) {
		clips.add(0, clip);
	}
	
	public List<AudioClip> getClips() {
		return clips;
	}
	
	public void clear() {
		clips.clear();
	}
	
	@Override
	public float getDuration() {
		float duration = 0;
		for (AudioClip clip : clips) {
			duration += clip.getDuration();
		}
		return duration;
	}

	@Override
	public float getMaxAmp() {
		float maxAmp = 0;
		for (AudioClip clip : clips) {
			if (clip.getMaxAmp() > maxAmp) {
				maxAmp = clip.getMaxAmp();
			}
		}
		return maxAmp;
	}

	@Override
	public float getMinAmp() {
		float minAmp = 0;
		for (AudioClip clip : clips) {
			if (clip.getMaxAmp() < minAmp) {
				minAmp = clip.getMaxAmp();
			}
		}
		return minAmp;
	}

	@Override
	public float getSampleAtFrac(float frac) {
		return getSampleAtTime(frac * getDuration());
	}

	@Override
	public float getSampleAtTime(float time) {
		for (AudioClip clip : clips) {
			if (time < clip.getDuration()) {
				return clip.getSampleAtTime(time);
			} else {
				time -= clip.getDuration();
			}
		}
		if (clips.size() >= 1) {
			return clips.get(clips.size() - 1).getSampleAtTime(time);
		} else {
			return 0;
		}
	}

	@Override
	public float getVolume() {
		return getMaxAmp() - getMinAmp();
	}

}
